import json
import csv
from time import sleep

import requests
from Redis import RedisClient

class iDataLogin(object):
    r = RedisClient()

    def login(self, id, username, password):
        adsl = self.r.ADSL()
        proxies = {}
        if adsl:
            proxies = {
                'http': 'http://xiaohengheng:950218@' + adsl,
                'https': 'http://xiaohengheng:950218@' + adsl,
            }
        headers  = {
                'Host': 'user.cn-ki.net',
                'Connection': 'keep-alive',
                'Pragma': 'no-cache',
                'Cache-Control': 'no-cache',
                'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
                'Content-Type': 'application/json',
                'sec-ch-ua': '"Chromium";v="94", "Google Chrome";v="94", ";Not A Brand";v="99"',
                'sec-ch-ua-mobile': '?0',
                "sec-ch-ua-platform": "macOS",
                "Upgrade-Insecure-Requests": "1",
                "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36",
            # "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
                "Sec-Fetch-Site": "none",
                "Sec-Fetch-Mode": "navigate",
                "Sec-Fetch-Dest": "empty",
                "Referer": "https://user.cn-ki.net/login",
                "Accept-Encoding": "gzip, deflate, br",
                "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
                "x-dsa-originalip": "47.0.0.0",
                "x-dsa-secret": "DSA20130311X",
                "x-dsa-host": "ixueshu.com",
                'Cookie': f'num={username}'
            }
        url = f"https://user.cn-ki.net/api/login?num={username}&passwd={password}"
        print(url)
        loginResponse = requests.get(url, headers=headers, proxies=proxies)
        if loginResponse.status_code == 200:
            loginData = json.loads(loginResponse.text)
            if loginData['status'] == 1:
                self.r.client.hset('idata', f'{id}', json.dumps(loginData['data']))
            else:
                with open('data/error_account.csv', 'a+') as f:
                    f.writelines(f'{account},{password}\n')
        else:
            with open('data/maybe_error_account.csv', 'a+') as f:
                f.writelines(f'{account},{password}\n')



if __name__ == '__main__':
    bot = iDataLogin()
    # with open('', 'r') as f:
    index = 0
    for line in open("data/idata1116.csv"):
        data = line.strip()
        account = data.split(',')[0]
        print(account)
        password = data.split(',')[1]
        bot.login(index, account, password)
        index += 1
        print('sleep 5 ..')
        sleep(5)